package ru.reaperoq.taskmanager.services

import io.jsonwebtoken.Claims
import io.jsonwebtoken.Jwts
import io.jsonwebtoken.security.Keys
import org.springframework.beans.factory.annotation.Value
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.stereotype.Component
import org.springframework.stereotype.Service
import java.util.*


@Component
@Service
class JwtService(
    @Value("\${token.signing.key}")
    private val key: String
) {
    private val secret = Keys.hmacShaKeyFor(key.toByteArray())

    fun generateToken(
        userDetails: UserDetails,
        additionalClaims: Map<String, Any> = emptyMap()
    ): String =
        Jwts.builder()
            .claims()
            .subject(userDetails.username)
            .issuedAt(Date(System.currentTimeMillis()))
            .add(additionalClaims)
            .and()
            .signWith(secret)
            .compact()

    fun isValid(token: String, userDetails: UserDetails): Boolean {
        val username = extractUsername(token.replace(" ", ""))
        return username == userDetails.username
    }

    fun extractUsername(token: String): String? {
        println("TOKEN: $token")
        return extractClaims(token).subject
    }

    fun extractClaims(token: String): Claims =
        Jwts.parser()
            .verifyWith(secret)
            .build()
            .parseSignedClaims(token)
            .payload
}